import { toast } from "@/components/toast/toast";
import axios, { AxiosRequestConfig, AxiosResponse } from "axios";

// 设置默认的请求配置
// axios.defaults.baseURL = "http://192.168.150.188:8080"; // 设置接口基础地址
axios.defaults.baseURL = import.meta.env.VITE_URL_BASE;
// axios.defaults.baseURL = "https://dev_api.chainingview.io";   
// http://192.168.150.66:8080/api/v1/user/register

// 创建 Axios 实例
const api = axios.create({
    timeout: 10000
});
const againNum = 2;
const againTime = 2000;
// 请求拦截器
api.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        // 在这里可以添加额外的请求头等逻辑

        // 从本地存储或其他地方获取 token，并设置到请求头
        const token = localStorage.getItem("token");
        //当前语言
        // let language = localStorage.getItem("language");
        let language = localStorage.getItem('language') || "en";
        if (token && !config.url?.includes("/login")) {
            config.headers!["Authorization"] = `Bearer ${token}`;
        }
        if (token && config.url?.includes("/login/logs")) {
            config.headers!["Authorization"] = `Bearer ${token}`;
        }
        if (language) {
            if (language == "zh") language = "zh-TW"; 
            config.headers!["lang"] = language;
            // console.log(language, "languagelanguagelanguage");

        }
        // if (token && !config.url?.includes("/login")) {
        //     config.headers!["token"] = token;
        // }

        return config;
    },
    error => {
        // 处理请求错误
        return Promise.reject(error);
    }
);
// 统一处理请求失败的函数
function handleRequestError<T>(error: any, request: any, maxRetry: number): Promise<T> {
    if (error.request) {
        return new Promise<T>((resolve, reject) => {
            setTimeout(() => {
                request(maxRetry - 1);
            }, againTime);
        });
    } else {
        // 其他错误，返回空对象或进行其他处理
        return Promise.reject({} as T);
    }
}

// GET 方法封装
export const get = <T>(url: string, params?: any, maxRetry = againNum): Promise<T> => {
    return new Promise<T>((resolve, reject) => {
        const request = (maxRetry: number) => {
            // console.log('request#########', maxRetry)
            if (maxRetry >= 0) {
                api.get(url, { params })
                    .then((response: AxiosResponse<any>) => {
                        if (response.data.code == 405) {
                            reset(response.data);
                        } else {
                            resolve(response.data);
                        }

                        if (response.data.code != 200) {
                            if (url.includes("/api/user")) {

                            }

                        }
                    })
                    .catch(error => {
                        // resolve({} as any);
                        console.error("request bad!!! get #########################################", error);
                        handleRequestError<T>(error, request, maxRetry - 1)
                            .then((result: T) => resolve(result))
                            .catch((err: any) => reject(err));
                    });
            } else {
                console.log("get 超过最大重试次数，返回错误信息", url);
                reject("request bad!!!");
            }
        };
        request(maxRetry);
    });
};

// POST 方法封装
export const post = <T>(url: string, data?: any, isJson = false, maxRetry = againNum): Promise<T> => {
    let param = data;
    const headers: any = {};
    if (!isJson) {
        const formdata = new FormData();
        for (let i in data) {
            formdata.append(i, data[i]);
        }
        param = formdata;
        headers["Content-Type"] = "application/x-www-form-urlencoded";
    }
    return new Promise<T>((resolve, reject) => {
        const request = (maxRetry: number) => {
            if (maxRetry >= 0) {
                api.post(url, param, {
                    headers
                })
                    .then((response: AxiosResponse<any>) => {
                        // console.log("34545454", response.data)
                        if (response.data.code == 405) {
                            reset(response.data);
                        } else {
                            resolve(response.data);
                        }
                    })
                    .catch(error => {
                        // resolve({} as any);
                        // console.error("request bad!!! post #########################################", error);
                        handleRequestError<T>(error, request, maxRetry - 1)
                            .then((result: T) => resolve(result))
                            .catch((err: any) => reject(err));
                    });
            } else {
                reject("request bad!!!");
            }
        };
        request(maxRetry);
    });
};

function reset(data: any) {
    toast(data.info);
    // localStorage.removeItem("token");
    // setTimeout(() => {
    //     location.href = location.origin + "/home";
    // }, 3000);
}
